﻿using UnityEngine;
namespace Core
{
    /// <summary>
    /// 单位存活状态
    /// </summary>
    public enum UnitSurvivalState
    {
        /// <summary>
        /// 活着
        /// </summary>
        Alive = 0,
        /// <summary>
        /// 冻结
        /// </summary>
        Freeze,
        /// <summary>
        /// 死亡
        /// </summary>
        Death,
        /// <summary>
        /// 死亡回收
        /// </summary>
        Recycle
    }
    
    public class Unit : Entity, IAwake<int, Transform>
    {
        public int id { get; private set; }
        public Transform transform;
        public Transform model { get; private set; }

        public float collideWidth;
        public float collideHeight;
        private UnitSurvivalState state;
        public bool IsCanTarget => SurvivalState != UnitSurvivalState.Death && SurvivalState != UnitSurvivalState.Recycle;

        public StateType stateType => StateType.Move;

        public bool IsMove => stateType == StateType.Idle;

        public UnitSurvivalState SurvivalState
        {
            get => state;
            set
            {
                if (state == value)
                    return;

                World.GetComponent<EventComponent>().Publish(new UnitStateChange { unit = this, oldState = state, newState = value });
                state = value;
            }
        }

        public Vector3 Position
        {
            get => transform.position;
            set => transform.position = value;
        }

        public Vector3 Forward
        {
            get => transform.forward;
        }

        public Vector3 Scale
        {
            get => transform.localScale;
            set => transform.localScale = value;
        }

        public Quaternion Rotation
        {
            get => transform.rotation;
            set => transform.rotation = value;
        }

        public Animator Animator => transform.GetComponentInChildren<Animator>();

        void IAwake<int, Transform>.Awake(int id, Transform transform)
        {
            this.id = id;
            var config = World.GetComponent<ConfigComponent>().GetConfig<UnitConfig>(id);
            var root = new GameObject(config.name);
            transform.SetParent(root.transform, true);
            model = transform;
            this.transform = root.transform;
        }


        public override void Dispose()
        {
            World.GetComponent<UnitComponent>()?.Remove(this.InstanceId);

            base.Dispose();

            SurvivalState = UnitSurvivalState.Recycle;
            if (transform != null)
            {
                GameObject.Destroy(transform.gameObject);
                transform = null;
            }
        }

    }

}